package com.pateo.retail.canal.handler.es;

import com.pateo.retail.canal.es.EsService;
import com.pateo.retail.canal.es.vo.EsUpsertReqVo;
import com.pateo.retail.canal.model.AllEsCustomerInfo;
import com.pateo.retail.canal.model.LabelCustomer;
import com.pateo.retail.canal.utils.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@CanalTable(value = "label_customer")
public class LabelCustomerHandler implements EntryHandler<LabelCustomer> {

    private Logger logger = LoggerFactory.getLogger(CustomerActionLogHandler.class);

    private final static String ADD_SCRIPT1 = "ctx._source.%s.add(params.%s)";


    private final static String ADD_SCRIPT = "if (ctx._source.%s == null) {ctx._source.%s = [params.%s]} else {ctx._source.%s.add(params.%s)}";


    private final static String REMOVE_SCRIPT = "ctx._source.%s.remove(ctx._source.%s.indexOf(params.%s))";

    @Autowired
    private EsService esService;


    @Override
    public void insert(LabelCustomer labelCustomer) {
        logger.info("insert message  {}", labelCustomer);

        if (StringUtils.isEmpty(labelCustomer.getTenant_code())) {
            logger.info("数据异常tenantCode为null，不执行同步es同步逻辑-----{}", labelCustomer);
            return;
        }

        try {

            AllEsCustomerInfo customerInfo = esService.get(CommonUtils.getEsIndex(labelCustomer.getTenant_code()), labelCustomer.getCustomer_id() + "", AllEsCustomerInfo.class);
            if (customerInfo == null || (customerInfo != null && customerInfo.getLabel_id_list() == null && customerInfo.getLabel_value_list() == null)) {
                EsUpsertReqVo reqVo = new EsUpsertReqVo();
                reqVo.setData(labelCustomer);
                reqVo.setIndex(CommonUtils.getEsIndex(labelCustomer.getTenant_code()));
                reqVo.setId(labelCustomer.getCustomer_id() + "");
                esService.upsert(reqVo);
            }
            coverAdd(labelCustomer);

        } catch (Exception e) {
        }
    }

    @Override
    public void update(LabelCustomer before, LabelCustomer after) {
        logger.info("update before {} ", before);
        logger.info("update after {}", after);

        if (StringUtils.isEmpty(after.getTenant_code())) {
            logger.info("数据异常tenantCode为null，不执行同步es同步逻辑-----{}", after);
            return;
        }

        AllEsCustomerInfo customerInfo = esService.get(CommonUtils.getEsIndex(after.getTenant_code()), after.getCustomer_id() + "", AllEsCustomerInfo.class);

        if (customerInfo != null && !CollectionUtils.isEmpty(customerInfo.getLabel_id_list())) {
            coverUpdate(customerInfo.getLabel_id_list(), before.getLabel_value_sid(), after.getLabel_value_sid());
        }
        if (customerInfo != null && !CollectionUtils.isEmpty(customerInfo.getLabel_id_list())) {
            coverUpdate(customerInfo.getLabel_value_list(), before.getLabel_value_name(), after.getLabel_value_name());
        }

        EsUpsertReqVo reqVo = new EsUpsertReqVo();
        reqVo.setData(customerInfo);
        reqVo.setIndex(CommonUtils.getEsIndex(after.getTenant_code()));
        reqVo.setId(after.getCustomer_id() + "");
        esService.upsert(reqVo);
    }

    @Override
    public void delete(LabelCustomer labelCustomer) {
        logger.info("delete  {}", labelCustomer);

        if (StringUtils.isEmpty(labelCustomer.getTenant_code())) {
            logger.info("数据异常tenantCode为null，不执行同步es同步逻辑-----{}", labelCustomer);
            return;
        }

        coverRemove(labelCustomer);
        // 每次删除判断一下数组是否为[]或者null 然后把es里面的数组更新成为null
        AllEsCustomerInfo customerInfo = esService.get(CommonUtils.getEsIndex(labelCustomer.getTenant_code()), labelCustomer.getCustomer_id() + "", AllEsCustomerInfo.class);
        // 把数据更新为null
        if (CollectionUtils.isEmpty(customerInfo.getLabel_id_list())) {
            customerInfo.setLabel_id_list(null);
            customerInfo.setLabel_value_list(null);
            logger.info("label_id_list 数据信息已为空,更新label_value_list为null");
            EsUpsertReqVo reqVo = new EsUpsertReqVo();
            reqVo.setData(customerInfo);
            reqVo.setIndex(CommonUtils.getEsIndex(labelCustomer.getTenant_code()));
            reqVo.setId(labelCustomer.getCustomer_id() + "");
            //esService.upsert(reqVo);
        }
    }

    /**
     * @param list
     * @param target
     * @param <E>
     */
    /*public static <E> void coverRemove(List<E> list, E target) {
        for (E item : list) {
            if (item.equals(target)) {
                list.remove(item);
                break;
            }
        }
    }*/
    public static <E> void coverUpdate(List<E> list, E target, E resources) {
        for (E item : list) {
            if (item.equals(target)) {
                list.remove(item);
                list.add(resources);
                break;
            }
        }
    }


    /**
     * 添加更新数据处理
     *
     * @param labelCustomer
     */
    private void coverRemove(LabelCustomer labelCustomer) {
        // 往主文档label_value_list这个数组里面加数据
        String valueScript = String.format(REMOVE_SCRIPT, "label_value_list", "label_value_list", "label_value_list");
        Map<String, Object> valueMap = new HashMap<>();
        valueMap.put("label_value_list", labelCustomer.getLabel_value_name());
        esService.updateByScript(CommonUtils.getEsIndex(labelCustomer.getTenant_code()), labelCustomer.getCustomer_id() + ""
                , valueScript, valueMap);
        // 往主文档label_id_list这个数组里面加数据
        String idScript = String.format(REMOVE_SCRIPT, "label_id_list", "label_id_list", "label_id_list");
        Map<String, Object> idMap = new HashMap<>();
        idMap.put("label_id_list", labelCustomer.getLabel_value_sid());
        esService.updateByScript(CommonUtils.getEsIndex(labelCustomer.getTenant_code()), labelCustomer.getCustomer_id() + ""
                , idScript, idMap);
    }

    private void coverAdd(LabelCustomer labelCustomer) {
        // if (ctx._source.%s == null) {ctx._source.%s = [params.%s]} else {ctx._source.%s.add(params.%s)}
        logger.info("***********开始添加LabelCustomer****************");
        // 往主文档label_value_list这个数组里面加数据
        String valueScript = String.format(ADD_SCRIPT, "label_value_list", "label_value_list", "label_value_list", "label_value_list", "label_value_list");
        Map<String, Object> valueMap = new HashMap<>();
        valueMap.put("label_value_list", labelCustomer.getLabel_value_name());
        esService.updateByScript(CommonUtils.getEsIndex(labelCustomer.getTenant_code()), labelCustomer.getCustomer_id() + ""
                , valueScript, valueMap);
        // 往主文档label_id_list这个数组里面加数据
        String idScript = String.format(ADD_SCRIPT, "label_id_list", "label_id_list", "label_id_list", "label_id_list", "label_id_list");
        Map<String, Object> idMap = new HashMap<>();
        idMap.put("label_id_list", labelCustomer.getLabel_value_sid());
        esService.updateByScript(CommonUtils.getEsIndex(labelCustomer.getTenant_code()), labelCustomer.getCustomer_id() + ""
                , idScript, idMap);
    }
}
